from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from django.views.generic import ListView, DetailView

from .models import Book


def index(request):
    """
    取出所有书的记录，把书的名字列出来，一行一个，
    通过点击书名，可以打开详情页。
    """
    books = Book.objects.all()
    candy = {'count': 0}
    return render(request, "book/index.html", {'books': books, 'candy': candy})


def detail(request, pk):
    book = get_object_or_404(Book, pk=pk)
    return render(request, "book/detail.html", {'book': book})


class BookListView(ListView):

    context_object_name = 'books'
    template_name = 'book/index.html'

    def get_queryset(self):
        return Book.objects.filter(year=self.kwargs['year'])

    def get_context_data(self, **kwargs):
        context = ListView.get_context_data(self, **kwargs)
        context['extra'] = '这是增加的额外信息'
        return context


class BookDetailView(DetailView):
    model = Book
